<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 设计变更管理 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel == 0 ? {} : rules"
    >
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="基本信息"></title-name>
          <custom-form :formList="formList" :form="form" :is-emit="false" :editModel="editModel == 0 ? '' : ''">
            <!-- 报送资料上传 --> 
            <template #fileList>
              <span class="fileList-tip" v-if="editModel == 2">*</span>
              <template v-if="editModel != 0 && editModel*1!==3">
                <l-table businessCode="BM27" :uploadArrys.sync="form.fileList"></l-table>
              </template>
              <file-link v-else :fileList="form.fileList" style="margin-top: -3px"></file-link>
            </template>
          </custom-form>
        </a-card>
      </a-spin>
    </a-form-model>
    <a-form-model  v-if="editModel==3 || isShowFile"
      ref="ruleTwoForm"
      :model="formTwo"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel == 0 ? {} : rulesTwo"
    >
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false" >
          <title-name title="基本信息"></title-name>
          <custom-form :isEmit="false" :formList="formListTwo" :form="formTwo" :editModel="''" @select="selectOrg">
            <!-- 确认资料上传 -->
            <template #fileList>
              <template v-if="editModel != 0">
                <l-table businessCode="BM27" :uploadArrys.sync="formTwo.fileList"></l-table>
              </template>
              <file-link v-else :fileList="formTwo.fileList" style="margin-top: -3px"></file-link>
            </template>
          </custom-form>
        </a-card>
      </a-spin>
    </a-form-model>
       <!-- 页脚操作栏 -->
        <div class="btn_box page-btn-right-top" v-if="editModel != 0">
          <a-button
            class="button_right"
            v-if="form.status == 'REJECTED'"
            type="primary"
            :loading="loadingBtn.REJECTED"
            @click="handleSubmit('REJECTED')"
            >保存</a-button
          >
          <span v-else>
            <a-button  v-if="this.editModel != 3"
              class="button_right"
              type="primary"
              :loading="loadingBtn.DRAFT"
              @click="handleSubmit('DRAFT')"
              >保存草稿</a-button>
          </span>
          <a-button
             v-if="this.editModel == 3"  class="button_right" type="primary" :loading="loadingBtn.FILE"  @click="infoFile('FILE')"
            >提交</a-button>
           <a-button v-else class="button_right" type="primary"   :loading="loadingBtn.SUBMITTED" @click="handleSubmit('SUBMITTED')"
            >提交</a-button>
          <a-button @click="handleActiveClose">关闭</a-button>
        </div>
        <div class="btn_box page-btn-right-top" v-else>
          <a-button @click="handleActiveClose">关闭</a-button>
        </div>
      <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { addDesignChange,updateDesignChange,getDesignChangeDetail,getCheckName} from '@/api/businessAffairs/designChange' // api
import { createValidator,positiveNumberReg} from '@/utils/regExpression.js'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BSelect from '@/components/BComponents/BSelect'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    SelectProject,
    BSelect,
    SelectSubCompany
  },
  data() {
    return {
      loading: false, // 加载控件
      visible: false, //人员选择控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增;3信息归档中
      form: {fileList:[],designId:null,projectId:null}, // 表单
      formTwo:{},
      designChangeName:null,
      isShowFile:false, //查看是是否显示归档详情
      CheckNameDisabled: null, //是否禁用名称
      id: '',
      dropDownChoiceData:[], //签证名字
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false,
        FILE:false,
      },
      rules: {
        name: [{ required: true, message: '请选择名称' }],
        submitAndSendTime: [{ required: true, message: '请选择报送时间', trigger: 'change' }],
        submitAndSendMoney: [
          { required: true, message: '请输入报送金额(含税)(元)', trigger: 'blur' },
          { validator: createValidator(positiveNumberReg, '数字2位小数'), trigger: 'blur' },
        ],
        costAmount: [
          { required: true, message: '请输入对应成本(含税)(元）', trigger: 'blur' },
          { validator: createValidator(positiveNumberReg, '数字并最多2位小数'), trigger: 'blur' },
        ],
        fileList: [{ required: true, message: '请上传报送资料上传' }],
      }, // 校验规则
      rulesTwo:{
        confirmMoney: [
          { required: true, message: '请输入确认金额(含税)(元)', trigger: 'blur' },
          { validator: createValidator(positiveNumberReg, '数字并最多2位小数'), trigger: 'blur' },
        ],
        auditTime: [{ required: true, message: '请选择审定时间', trigger: 'change' }],
      },
      init: false, // 初始化控件
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.editModel = 0
          })
        }
      }
    },
    //确认金额(含税)(元)
    'formTwo.confirmMoney'(newVal) {
      let rate = this.form.costAmount ? (((newVal * 1 - this.form.costAmount * 1)/this.form.costAmount * 1)*100).toFixed(2): 0;
      this.$set(this.formTwo, 'profitMargin', rate)
    },
  },
  created() {},
  async mounted() {
    this.$route.meta.title = ['设计变更管理 查看', '设计变更管理 编辑', '设计变更管理 新增','信息归档中'][this.editModel]
   if (this.editModel != 2) {
         await this.getDetailData()
    } else {
      this.form.projectId = this.$userInfo().currentPost.projectId;
      this.$nextTick(() => {
        // 默认映射联系人为登陆人
         this.form.fillName=  this.$userInfo().name
         this.form.fillId = this.$userInfo().id;
          this.form.fillTime = this.$dateFormat(new Date(), 'D')
        this.init = true
      })
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('comm_design_change_management')
  },
  computed: {
    formList() {
      return [
          {
              label: '所属单位',
              type: 'orgTree',
              keyName: 'projectId',
              rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
              span: 16,
              isAutoSelectFirst: true,
              isNeedAuth:true ,
              checkStrictly: true,
              disabled: true,
              viewName: "viewName",
          },
        // {
        //   type: SelectSubCompany,
        //   keyName: 'branchCompanyId',
        //   label: '所属分公司',
        //   placeholder: '自动带出',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '所属项目',
        //   placeholder: '自动带出',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2,
        //     keyValue: 'branchCompanyId',
        //     isClear: this.editModel == 2,
        //     isEdit: this.editModel != 2,
        //     form: this.form
        //   }
        // },
         {
          keyName: 'name',
          type: BSelect,
          disabled: this.editModel == 0 || this.editModel ==3,
          label: '名称',
          attrs: {
            form: this.form,
            request: this.getNameList
          },
          selectChange: (e) => {
            //切换名称获取数据
               this.form.downTime = e.receiptDate
               this.form.contentInfo = e.options
               this.form.factFinishTime = e.actualEnd || ""
               this.designChangeName = e.name;
          }
        },
        {
          keyName: 'downTime',
          type: 'a-date-picker',
          placeholder: '根据选择名称自动带出',
          disabled: true,
          label: '下发时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'factFinishTime',
          type: 'a-date-picker',
          placeholder: '根据APP填报时间自动带出',
          disabled: true,
          label: '实施完成时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'submitAndSendTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          disabled: this.editModel == 0 || this.editModel ==3,
          label: '报送时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'submitAndSendMoney',
          type: 'BaseInput',
          disabled: this.editModel == 0 || this.editModel ==3,
          label: '报送金额(含税)(元)'
        },
         {
          keyName: 'costAmount',
          type: 'BaseInput',
          disabled: this.editModel == 0 || this.editModel ==3,
          label: '对应成本(含税)(元）'
        },
          {
          keyName: 'fillName',
          type: 'BaseInput',
          disabled: true,
          label: '填报人'
        },
        {
          keyName: 'fillTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          disabled: true,
          label: '填报时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'contentInfo',
          type: 'BaseTextarea',
          disabled: true,
          label: '内容摘要',
          span: 24,
          hidden: this.isThreeMonitoringContent,
        },
        {
          slot: true,
          keyName: 'fileList',
          disabled: this.editModel == 0 || this.editModel ==3,
          label: '报送资料上传',
          span: 24
        }
      ]
    },
    formListTwo() {
       return [
        {
          keyName: 'confirmMoney',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '确认金额(含税)(元)'
         },
         {
          keyName: 'profitMargin',
          type: 'BaseInput',
          label: '利润率',
          disabled: true,
         },
          {
          keyName: 'auditTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          disabled: this.editModel == 0,
          label: '审定时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
         {
          slot: true,
          keyName: 'fileList',
          label: '确认资料上传',
          span: 24
        }
       ]
     }
  },
  methods: {
    //选择单位
    selectOrg(val) {
        if (val && val.length) {
            this.form.branchComId = val[val.length - 2].orgId
        }
    },
    async getNameList() {
       return  getCheckName()
          .then((res) => {
            this.CheckNameDisabled = res.data.length ? false : true //有数据才能选中
              if(this.editModel * 1===2 && !res.data.length){     //新增时和签证名称数据不存在，提示不能新增
                  this.$message.warning('名称无数据,不能新增');
              }
             return { code: 200, data: res.data }
          })
          .catch(() => {
            return { code: 200, data: [] }
          })
    },
    validateForm() {
      let flag = false
      if(this.editModel == 3){
        this.$refs.ruleTwoForm && this.$refs.ruleTwoForm.validate((e) => {
        if (e) {
          flag = true
        } else {
          this.$message.warning('请填写完所有必填项信息')
        }
       })
      }else{
        this.$refs.ruleForm.validate((e) => {
        if (e) {
          flag = true
        }else {
          this.$message.warning('请填写完所有必填项信息')
        }
       })
      }

      return flag
    },
    getDetailData() {
      // 不为添加时请求详情
      if (this.editModel != 2) {
        this.loading = true
        getDesignChangeDetail({ id: this.id })
          .then((res) => {
            this.loading = false
            res.data.projectId =  res.data.projectId.toString();
            this.form = { ...this.form, ...res.data }
            this.form.designId = res.data.designId;
            if(res.data.archiveBusinessDetailVO){
              this.formTwo = res.data.archiveBusinessDetailVO;
              this.isShowFile = true;
            }
            this.$nextTick(() => {
              this.init = true
            })
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        this.$nextTick(() => {
          this.init = true
        })
      }
    },
    /**
     * 提交表单
     */
    handleSubmit(status) {
      this.setProcessConfig = null;
      if (status == 'SUBMITTED' && !this.validateForm()) {
        return
      }
      this.loading = true
      this.loadingBtn[status] = true
      this.form.designId =this.form.designId?this.form.designId:this.form.name;
      let form = this.$clone(this.form);
      if(!form.archiveBusinessDetailVO){
        delete form.archiveBusinessDetailVO;
      }
      form.name = this.designChangeName || form.name;
     if (status != 'REJECTED') {
        form.status = status == 'SUBMITTED' ? 1 : 0
      } else {
        form.status = 5
      }
      let api = updateDesignChange;
     this.submitApprovalConfirm(status == 'SUBMITTED'?this.processConfig:6,(flag)=>{
       if(!flag) {
         this.loading = false
         this.loadingBtn[status] = false
         return
       }
      api(form)
        .then((res) => {
          this.loading = false
          this.loadingBtn[status] = false
          this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
          if(status =='SUBMITTED') {
            //提交时，返回id
                this.businessId = res.data || this.id;
                this.setProcessConfig = this.processConfig;
                return
            }else{
              this.$multiTab.close()
              }
        })
        .catch(() => {
          this.loadingBtn[status] = false
          this.loading = false
          this.$message.warning(err.data.message)
        })
     })
    },
    /**
     信息归档中提交
     */
    infoFile(status){
      if (status == 'FILE' && !this.validateForm()) {
        return
      }
      this.loading = true
      this.loadingBtn[status] = true
      let formTwo = this.$clone(this.formTwo);
      formTwo.status = 7;
      formTwo.designChangeId = this.id;
      let api = addDesignChange;
      api(formTwo)
        .then(() => {
          this.loading = false
          this.loadingBtn[status] = false
          this.$message.success('信息归档成功')
          this.$multiTab.close()
        })
        .catch(() => {
          this.loadingBtn[status] = false
          this.loading = false
          this.$message.warning(err.data.message)
        })
    }
  },

}
</script>
<style lang="less" scoped>
.fileList-tip{
    position: absolute;
    z-index: 1000;
    left: -109px;
    top: -3px;
    color: red;
}
</style>
